package cn.xlmdz.subsoilerinfoquery.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.CoordinateConverter;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.PolygonOptions;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.amap.api.maps2d.model.TileOverlayOptions;
import com.amap.api.maps2d.model.UrlTileProvider;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xlmdz.subsoilerinfoquery.bean.ContourBean;
import cn.xlmdz.subsoilerinfoquery.bean.LonLatBean;
import cn.xlmdz.subsoilerinfoquery.databinding.ActivityMapBinding;
import cn.xlmdz.subsoilerinfoquery.http.ApiEngine;
import cn.xlmdz.subsoilerinfoquery.http.ApiServices;
import cn.xlmdz.subsoilerinfoquery.utils.SharedPrefsUtil;
import cn.xlmdz.subsoilerinfoquery.view.LoadingDialog;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MapActivity extends AppCompatActivity {

    private ActivityMapBinding viewBinding;
    private LoadingDialog loadingDialog;
    private AMap mAMap;

    private String cid, date, position, terminal;
    private double area;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivityMapBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        viewBinding.map.onCreate(savedInstanceState);
        if (mAMap == null) {
            mAMap = viewBinding.map.getMap();
            mAMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            mAMap.setTrafficEnabled(true);

            // 去除右下角的缩放等级按钮
            mAMap.getUiSettings().setZoomControlsEnabled(false);

            addRemoteOverlay();
        }

        Intent intent = getIntent();
        cid = intent.getStringExtra("cid");
        date = intent.getStringExtra("date");
        position = intent.getStringExtra("position");
        terminal = intent.getStringExtra("terminal");
        area = intent.getDoubleExtra("area", 0);

        initToolbar();

        getCarListData();
//        getContourData();

        initViews();
    }

    private void initToolbar() {
        viewBinding.tvTitleTitle.setText(terminal);
        viewBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initViews() {
        viewBinding.tvWorkLocation.setText(position);
        viewBinding.tvWorkArea.setText(area + "亩");
        viewBinding.tvWorkDate.setText("作业日期：" + date);
    }

    private void getContourData() {
        String token = SharedPrefsUtil.getStringPreference(this, "loginToken");
        if (!TextUtils.isEmpty(token)) {
            ApiServices services = ApiEngine.getInstance().getApiService();
            Map<String, String> params = new HashMap<>();
            params.put("id", cid);
            params.put("begin", date);
            params.put("end", date);
            params.put("oneday", "1");
            Observable<ContourBean> observable = services.getContourData(token, params);
            observable.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<ContourBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            showLoading();
                        }

                        @Override
                        public void onNext(@NonNull ContourBean carDataBean) {
                            if (carDataBean.getData().getLnglats().size() > 0) {
                                List<List<List<Double>>> pointList = carDataBean.getData().getLnglats().get(0);
                                AddPloygon(pointList);
                            }
                            hideLoading();
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            hideLoading();
                        }

                        @Override
                        public void onComplete() {
                            hideLoading();
                        }
                    });
        }
    }

    private void getCarListData() {
        String token = SharedPrefsUtil.getStringPreference(this, "loginToken");
        if (!TextUtils.isEmpty(token)) {
            ApiServices services = ApiEngine.getInstance().getApiService();
            Map<String, String> params = new HashMap<>();
            params.put("id", cid);
            params.put("begin", date + " 00:00:00");
            params.put("end", date + " 23:59:59");
            Observable<LonLatBean> observable = services.getLonLatData(token, params);
            observable.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<LonLatBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            showLoading();
                        }

                        @Override
                        public void onNext(@NonNull LonLatBean carDataBean) {
                            AddPolyline(carDataBean.getData().getPosition());
                            hideLoading();
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            hideLoading();
                        }

                        @Override
                        public void onComplete() {
                            hideLoading();
                        }
                    });
        }
    }

    /***
     * 在地图上添加线条
     * @param positions
     */
    private void AddPolyline(List<LonLatBean.Data.Position> positions) {
        List<LatLng> latLngs = new ArrayList<LatLng>();
        CoordinateConverter converter = new CoordinateConverter();
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        for (int i = 0; i < positions.size(); i++) {
            LatLng sourceLatLng = new LatLng(Double.parseDouble(positions.get(i).getLatitude()), Double.parseDouble(positions.get(i).getLongitude()));
            // sourceLatLng待转换坐标点 LatLng类型
            converter.coord(sourceLatLng);
            // 执行转换操作
            LatLng desLatLng = converter.convert();
            latLngs.add(desLatLng);
        }
        //将地图移动到定位点
        if (latLngs.size() > 0) {
            mAMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngs.get(0)));
            //起点位置和  地图界面大小控制
            mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngs.get(0), 16));
            Polyline polyline = mAMap.addPolyline(new PolylineOptions().width(5).color(Color.argb(255, 16, 219, 189)).
                    addAll(latLngs));
        }
    }

    /***
     * 在地图上添加多边形面
     * @param pointList
     */
    private void AddPloygon(List<List<List<Double>>> pointList) {
        CoordinateConverter converter = new CoordinateConverter();
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        LatLng centerPoint = null;

        for (int i = 0; i < pointList.size(); i++) {
            List<LatLng> latLngs = new ArrayList<LatLng>();
            for (int j = 0; j < pointList.get(i).size(); j++) {
                LatLng sourceLatLng = new LatLng(pointList.get(i).get(j).get(1), pointList.get(i).get(j).get(0));
                // sourceLatLng待转换坐标点 LatLng类型
                converter.coord(sourceLatLng);
                // 执行转换操作
                LatLng desLatLng = converter.convert();
                latLngs.add(desLatLng);
                centerPoint = desLatLng;
            }
            // 声明 多边形参数对象
            PolygonOptions polygonOptions = new PolygonOptions();
            // 添加 多边形的每个顶点（顺序添加）
            polygonOptions.addAll(latLngs);
            polygonOptions.strokeWidth(3) // 多边形的边框
                    .strokeColor(Color.argb(255, 16, 219, 189)) // 边框颜色
                    .fillColor(Color.argb(255, 16, 219, 189));   // 多边形的填充色
            mAMap.addPolygon(polygonOptions);
        }

        //将地图移动到定位点
        mAMap.moveCamera(CameraUpdateFactory.changeLatLng(centerPoint));
        //起点位置和  地图界面大小控制
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerPoint, 16));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        viewBinding.map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        viewBinding.map.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        viewBinding.map.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        viewBinding.map.onSaveInstanceState(outState);
    }

    void addRemoteOverlay() {
        final String url = "https://mt3.google.cn/maps/vt?lyrs=y@194&hl=zh-CN&gl=cn&x=%d&y=%d&z=%d";
        TileOverlayOptions tileOverlayOptions = new TileOverlayOptions().tileProvider(new UrlTileProvider(256, 256) {
            @Override
            public URL getTileUrl(int x, int y, int zoom) {
                try {
                    return new URL(String.format(url, x, y, zoom));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        tileOverlayOptions.diskCacheEnabled(true)
                .diskCacheDir("/storage/emulated/0/amap/OMCcache")
                .diskCacheSize(100000)
                .memoryCacheEnabled(true)
                .memCacheSize(100000)
                .zIndex(-9999);
//        googleTileOverlay = mAMap.addTileOverlay(tileOverlayOptions);
        mAMap.addTileOverlay(tileOverlayOptions);
    }

    public void showLoading() {
        if (loadingDialog == null)
            loadingDialog = new LoadingDialog(this, "加载中…");
        if (!loadingDialog.isShowingNew())
            loadingDialog.show();
    }

    public void hideLoading() {
        if (loadingDialog != null && loadingDialog.isShowingNew())
            loadingDialog.close();
    }
}